/**
 * Jquery UI and SoUI Bridage
 * 注意：需要在util-page之后引入
 * Created by Su on 2014-10-8.
 */

/**
 * 绑定表格中增删改查按钮事件
 * @since 1.0 2014-10-6 by sutroon
 */
function bind_table_curd_button_event() {


// 新增项目按钮点击 2014-8-12 by sutroon
    $('.lnk-add').unbind('click').click(function () {
        click_lnkAdd($(this));
        return false;
    })

// 编辑项目按钮 2014-8-12 by sutroon
    $('.lnk-edit').unbind('click').click(function () {
        click_lnkEdit($(this));
        return false;
    })

// 确认并执行按钮(用于删除项目等需要确认后操作的按钮) 2014-8-12 by sutroon created, 2014-9-24 by sutroon 新增data-show属性(值为page或dialog)，支持多次跳转操作.
// 服务端返回格式应为$this->result($result,'@密码重置%!');
    $('.lnk-confirm').unbind('click').click(function () {
        click_lnkConfirm($(this));
        return false;
    })

    // 批量勾选操作 2014-8-14 by sutroon
    $('.lnk-multiple-confirm').unbind('click').click(function () {
        click_lnkMultipleConfirm($(this));
        return false;
    })

    // 显示或隐藏复选框列 2014-8-13 by sutroon
    // @example <a href="#" class="button btn-icon lnk-multiple" data-table=".table-list">批量操作</a>
    $('.lnk-multiple').unbind('click').click(function () {
        var table = $(this).data('table');
        if (!table) {
            table = '.table-list';
        }
        setTableMultiple(table);
        return false;
    })

    // 设置表格的多选列 2014-10-8 by sutroon
    setTableMultiple('.table-multiple');

    // 设置超链接倒计时功能 2014-10-9 by sutroon
    $('.lnk-countdown').unbind('click').click(function () {
        return countDownAnchor($(this));
    })

}

/**
 * 批量选择并提交
 * @param url 递交url, 占位符varkey,提交时多个值之间以,隔开
 * @param table 表格选择器，如 .table-list
 * @param msg 提示消息
 * @param show 跳转方式(page|dialog)
 * @since 1.0 2014-10-30 by sutroon; 2015-2-12 新增在新窗口或页面中多次跳转的功能
 * @example multipleConfirmSubmit("{:U('CtiTask/task_delete_batch','show=dialog&ids=varkey')}");
 */
function multipleConfirmSubmit(url, table, msg, show) {
    if (!table) {
        table = '.table-list';
    }
    var $table = $(table);
    var $th = $table.find('thead th:first-child');
    if ($th.attr('class') == 'multipleCol') {
        var ids = getTableMultipleKeys($table);
        if (!ids) {
            alert('请勾选项目!');
            // $.somessager.alert('提示', '请勾选项目!');
            return;
        }
        if (!msg) {
            msg = '您确定要执行此操作吗?';
        }
        if (!confirm(msg)) {
            return;
        }
        url = url.replace('varkey', ids);
        if (show == 'page') {
            location.href = url;
            return false;
        }
        $.getJSON(url, function (data) {
            if (data.success) {
                refresh_page();
            } else {
                $.somessager.alert('结果', data.message);
            }
        });
    } else {
        $.somessager.alert('提示', '请勾选项目!');
    }
}

/**
 * 获取表格多选列中选中的值
 * 多个值以英文逗号隔开,否则返回空字符串
 * @param jQuery-Object $table
 * @returns string
 * @since 1.0 2014-12-29 by sutroon
 */
function getTableMultipleKeys($table) {
    var ids = '';
    $table.find('tbody td:first-child :checked').each(function () {
        ids += ',' + $(this).parent().parent().data('key');
    });
    return ids ? ids.substring(1) : ids;
}

/**
 * 设置表格的多选列
 * 可以同[批量操作]按钮一起使用
 * @since 1.0 2014-10-8 by sutroon
 * @example <table class="table-list table-multiple"></table>
 */
function setTableMultiple(table) {
    var $table = $(table);
    var $th = $table.find('thead th:first-child');
    if ($th.attr('class') == 'multipleCol') {
        $th.remove();
        $table.find('tbody td:first-child').remove();
    } else {
        $th.before('<th width="20" class="multipleCol"><input type="checkbox" onclick="checkAll(this)" /></th>');
        $table.find('tbody td:first-child').before('<td><input type="checkbox" /></td>');
    }
}

/**
 * 选择表格多选列的所有复选框
 * @param {checkbox} o checkbox对象
 * @returns {void}
 * @since 1.0 2014-8-13 by sutroon
 * @example <th><input type="checkbox" onclick="checkAll(this)" /></th>
 */
function checkAll(o) {
    $(o).parentsUntil('table').parent().find('td input:checkbox').prop('checked', $(o).prop('checked'));
}

/**
 * 检测变量键名是否存在
 * 用于url中的[键名]检测,如果存在则返回键名
 * @since 1.0 2014-9-24 by sutroon
 */
function check_varkey(str, varkey) {
    if (undefined == varkey) {
        varkey = '[key]';
    }
    if (str.indexOf(varkey) > -1) {
        return varkey;
    }
    varkey = encodeURI(varkey);
    if (str.indexOf(varkey) > -1) {
        return varkey;
    }
    return '';
}

/**
 * 获取行主键的值
 * @param {jQuery-object} $table jQuery包装好的Table对象
 * @returns {mixed} 返回<tr data-key="" />的属性值
 * @since 1.0 2014-8-13 by sutroon
 */
function getRowKey($table) {
    if ($table == undefined) {
        $table = $('.table-list');
    }
    return $table.find('tr.actived').data('key');
}

/**
 * 刷新页面
 * 用于iframe子页面调用
 * @since 1.0 2014-9-26 by sutroon
 * @example window.parent.refresh_page();
 */
function refresh_page() {
    // close_dialog();
    var domid = '#main-content';
    var $container = $(domid);
    if (!$container[0]) {
        alert('没有主容器!');
        return false;
    }
    // 2014-9-27 by sutroon 新增加载后方法委托,如<div id="main-content" data-func="config_table();"></div>
    var func = $container.data('func');
    $container.load(window.location.toString(), function () {
        config_table(); // 2014-9-28 by sutroon
        config_button(); // 2014-10-6 by sutroon
        bind_refresh_event();
        bind_table_curd_button_event(); // 2014-10-6 by sutroon
        if (func) {
            eval(func);
        }
    });
}

/**
 * 在页面中打开父窗体对话框
 * @param url 链接地址
 * @param settings 选项,如{title: 'Title', width: 400, height: 200}
 * @param ifrmName 窗口名称
 * @since 1.0 2014-10-11 by sutroon
 */
function open_dialog(url, settings, ifrmName, groupName, limit) {
    window.parent.open_dialog(url, settings, ifrmName, groupName, limit);
}


/**
 * 在页面中关闭父窗体对话框
 * @since 1.0 2014-10-29 by sutroon
 */
function close_dialog() {
    window.parent.close_dialog(window.name);
}

/**
 * 刷新父窗体对话框
 * @since 1.0 2014-10-14 by sutroon
 */
function resize_dialog(width) {
    window.parent.resize_dialog(window.name, width);
}

// 分页栏刷新图标点击效果 2014-9-26 改为局部刷新
function bind_refresh_event() {
    $('.lnk-refresh, .pager .pagination-load').click(function () {
        var domid = '#main-content';
        var $container = $(domid);
        // 2014-9-27 by sutroon 新增容器判断
        if (!$container[0]) {
            alert('没有主容器!');
            return false;
        }
        // 2014-9-27 by sutroon 新增加载后方法委托,如<div id="main-content" data-func="config_table();"></div>
        var func = $container.data('func');
        // location.reload();
        $container.load(window.location.toString(), function () {
            bind_refresh_event();
            config_table(); // 2014-9-28 by sutroon
            config_button(); // 2014-10-6 by sutroon
            bind_table_curd_button_event(); // 2014-10-6 by sutroon
            if (func) {
                eval(func);
            }
        });
        return false;
    })
    // 分页栏分页局部刷新效果 2014-9-26 by sutroon
    $('.pager a').click(function () {
        var href = $(this).attr('href');
        if (href.indexOf('javascript:') > -1) {
            return false;
        }
        $container.load(href, function () {
            bind_refresh_event();
            config_table(); // 2014-9-28 by sutroon
            if (func) {
                eval(func);
            }
        });
        return false;
    })
}

/**
 * 超链接按钮倒计时
 * @param $a jQuery封装好的超链接对象
 * @returns {boolean}
 * @since 1.0 2014-10-9 by sutroon
 * @example <a class="btn-refresh btn-icon lnk-countdown" href="#" data-interval="1000" data-count="5" data-func="func1()">刷新</a>
 */
function countDownAnchor($a) {
    if ($a.hasClass('ui-button-disabled')) {
        return false;
    }
    var func = $a.data('func');
    if (undefined !== func) {
        eval(func);
    }
    $a.button({disabled: true});
    var count = $a.data('count');
    if (undefined == count) {
        count = 5;
    }
    var i = count;
    var interval = $a.data('interval');
    if (undefined == interval) {
        interval = 1000;
    }
    var $btnTxt = $a.find('.ui-button-text');
    $btnTxt.append('<span>' + count + '</span>');
    var cd_btn = setInterval(switch_show, interval, $a);

    function switch_show($a) {
        i--;
        if (i < 1) {
            i = count;
            $a.button({disabled: false});
            $btnTxt.find('span').remove();
            clearInterval(cd_btn);
        }
        $btnTxt.find('span').text(i);
    }

    return false;
}

/**
 * 自动刷新页面局部内容
 * @param selector 容器选择器,&lt;span id="auto-refresh-page"&gt;&lt;/span&gt;
 * @param defaultTime 默认时间,默认30秒
 * @param minTime 最小时间,默认10秒,0=不限
 * @param func 定时执行的方法,如 refresh_page
 * @param isFirst 是否首次运行,放在局部刷新后操作的方法内时需填写false
 * @since 1.0 2014-10-30 by sutroon
 * @example
 *  1.在页面全局javascript中autoRefreshContent('#auto-refresh-page', 30, 10, refresh_page);
 *  2.在局部页面刷新后操作方法内autoRefreshContent('#auto-refresh-page', 30, 10, refresh_page, false);
 *  具体如：
 *      &lt;div id="main-content" data-func="config_main_table();"&gt;...&lt;span id="auto-refresh-page">&lt;/span&gt;...&lt;/div&gt;
 *      &lt;script&gt;
 *          function config_main_table(){
 *              ...
 *              autoRefreshContent('#auto-refresh-page', 30, 10, refresh_page, false);
 *          }
 *          config_main_table();
 *          autoRefreshContent('#auto-refresh-page', 30, 10, refresh_page);
 *      &lt;/script&gt;
 */
function autoRefreshContent(selector, defaultTime, minTime, func, isFirst) {
    if (undefined == window['auto_refresh_time']) {
        window['auto_refresh_time'] = defaultTime;
    }
    if ($(selector).html().length < 1) {
        $(selector).append('<input type="checkbox" value="1" /> <span>-</span>/<input type="text" size="2" value="' + window['auto_refresh_time'] + '" />秒');
    }
    $(selector + ' input:text').blur(function () {
        var val = $(this).val();
        if (isNaN(val)) {
            alert('请填写数值!');
            $(this).val(defaultTime);
            return;
        }
        if (minTime > 0 && val < minTime) {
            alert('最小值是' + minTime);
            $(this).val(defaultTime);
            return;
        }
        window['auto_refresh_time'] = val;
    })
    if (false === isFirst) {
        return;
    }
    $(selector + ' input:text').val(window['auto_refresh_time']);
    var i = 0;

    function refresh_this_page() {
        i++;
        $(selector + ' span').text(i);
        if (i >= window['auto_refresh_time']) {
            if (undefined !== func) {
                func();
            }
            i = 0;
        }
    }

    if (undefined !== si) {
        clearInterval(si);
    }
    var si = setInterval(refresh_this_page, 1000);
    if (undefined == $(selector + ' input:checked')[0]) {
        clearInterval(si);
    }
    $(selector + ' input:checkbox').click(function () {
        if ($(this).prop('checked')) {
            si = setInterval(refresh_this_page, 1000);
        } else {
            clearInterval(si);
        }
    })
}

/**
 * 点击新增项目按钮
 * 注意: 无需担心页面嵌套层数问题,每层都能直达顶层框架!
 * @param $a 包含lnk-add样式类的超链接对象
 * @since 1.0 2014-8-12 by sutroon; 1.1 2014-12-4 by sutroon 新增windowName参数控制是否唯一窗口
 * @example
 *  <a href="?s=User/admin_edit/show/dialog.html" class="lnk-add" data-dialog="{title:'新增管理员',width:400,height:360,closeable:false}">新增管理员</a>
 *  <a href="{:U('Order/order_edit')}" class="button btn-icon lnk-add" data-window-name="orderEdit">新增订单</a>
 */
function click_lnkAdd($a) {
    var settings = {title: $a.text(), width: 400, height: 200};
    var options = $a.data('dialog');
    if (options) {
        settings = $.extend(settings, eval('(' + options + ')'));
    }
    var url = $a.attr('href');
    var windowName = $a.data('windowName');
    open_dialog(url, settings, windowName);

}

/**
 * 编辑项目按钮
 * @param $a 包含.lnk-edit样式类的超链接对象
 * @returns {boolean}
 * @since 1.0 2014-8-12 by sutroon
 * @example <a href="?s=User/admin_edit/show/dialog/id/[key].html" class="lnk-edit" data-dialog="{title:'编辑管理员',width:400,height:360,closeable:false}">编辑管理员</a>
 */
function click_lnkEdit($a) {
    var url = $a.attr('href');
    var varkey = check_varkey(url);
    if (varkey) {
        var key = getRowKey();
        if (!key) {
            $.somessager.alert('提示', '请选中一行');
            return false;
        }
        url = url.replace(varkey, key);
    }
    // 2014-9-28 新增在新窗口或页面中多次次跳转的功能
    var show = $a.data('show');
    if (show == 'page') {
        location.href = url;
        return false;
    }
    var settings = {title: $a.text(), width: 400, height: 200};
    var options = $a.data('dialog');
    if (options) {
        settings = $.extend(settings, eval('(' + options + ')'));
    }
    open_dialog(url, settings);
}


/**
 * 点击确认并执行按钮
 * 用于删除项目等需要确认后操作的按钮(服务端返回格式应为$this->result($result,'@密码重置%!');)
 * @param $a 包含.lnk-confirm样式类的超链接对象
 * @since 1.0 2014-8-12 by sutroon created, 1.1 2014-9-24 by sutroon 新增data-show属性(值为page或dialog)，支持多次跳转操作.
 * @returns {void}
 * @example 
 * <a href="?s=User/password_reset/show/dialog/id/[key].html" class="lnk-confirm" data-confirm="{'message':'您确定要将密码重置为123456吗?'}">重置密码</a>
 * <a href="?s=User/password_reset/show/dialog/id/[key].html" class="lnk-confirm" data-confirm="您确定要将密码重置为123456吗?"  data-show="dialog">重置密码</a>
 * <a href="{:U('User/admin_delete','id='.$vo['id'])}" class="btn-minus btn-icon lnk-confirm" data-confirm="{'code':'password'}">删除租户</a>
 */
function click_lnkConfirm($a) {
    var url = $a.attr('href');
    var varkey = check_varkey(url);
    if (varkey) {
        var key = getRowKey();
        if (!key) {
            $.somessager.alert('提示', '请先选中一行!');
            return false;
        }
        url = url.replace(varkey, key);
    }
    var confirmdata = $a.data('confirm');
    var msg = '您确定要执行此操作吗?';
    if (undefined == confirmdata) {
        if (!confirm(msg)) {
            return false;
        }
    } else {
        if (confirmdata[0] == '{') {
            confirmdata = eval("(" + confirmdata + ")");
            msg = undefined == confirmdata.message ? '请输入口令' : confirmdata.message;
            if (undefined == confirmdata.code) {
                if (!confirm(msg)) {
                    return false;
                }
            } else {
                if (prompt(msg) !== confirmdata.code) {
                    alert('口令错误!')
                    return false;
                }
            }

        } else {
            if (!confirm(confirmdata)) {
                return false;
            }
        }
    }
    // 2014-9-24 新增在新窗口或页面中多次次跳转的功能
    var show = $a.data('show');
    if (show == 'dialog') {
        var settings = {title: $a.text(), width: 400, height: 200};
        var options = $a.data('dialog');
        if (options) {
            settings = $.extend(settings, eval('(' + options + ')'));
        }
        open_dialog(url, settings);
        return false;
    } else if (show == 'page') {
        location.href = url;
        return false;
    }
    $.getJSON(url, function (data) {
        if (data.success) {
            refresh_page();
            // location.reload();
        } else {
            $.somessager.alert('结果', data.message);
        }
    });
}


/**
 * 点击批量勾选按钮
 * @param $a 包含.lnk-multiple-confirm的超链接对象
 * @since 1.0 2014-8-14 by sutroon
 * @example <a href="?s=Article/news_list_delete/show/dialog/ids/[key].html" class="btn-minus btn-icon lnk-multiple-confirm" iconCls="icon-remove" data-table=".table-list">批量删除</a>
 */
function click_lnkMultipleConfirm($a) {
    var table = $a.data('table');
    if (!table) {
        table = '.table-list';
    }
    var msg = $a.data('confirm');
    if (!msg) {
        msg = '您确定要执行此操作吗?';
    }
    var url = $a.attr('href');
    var varkey = check_varkey(url);
    if (varkey) {
        url = url.replace(varkey, 'varkey');
    }
    var show = $a.data('show');
    multipleConfirmSubmit(url, table, msg, show);
}

/**
 * 排序按钮点击时间
 * <br />如：<a href="#" class="lnk-sort" onclick="return lnkSort_Click(this)" data-field="callSuccessCount">&uparrow;</a>
 * @param {type} a
 * @returns {Boolean}
 * @since 1.0 2015-2-2 by sutroon
 */
function lnkSort_Click(a) {
    var $this = $(a);
    var field = $this.data('field'); // id
    var direct = $this.data('direct'); // A=ASC|D=DESC
    if (undefined == field) {
        alert('未定义排序字段');
        return false;
    }
    direct = (!direct || 'A' == direct) ? 'D' : 'A';
    var sorts = 'sort/' + direct + field;
    var url = document.location.href.replace('#', '');
    url = url.replace(/\/sort\/\w+/g, '');
    if (url[url.length - 1] == '/') {
        url += 'index/' + sorts;
    } else if (url.substring(url.length - 5) == '.html') {
        url = url.substring(0, url.length - 5) + '/' + sorts + '.html';
    } else {
        url += '/' + sorts;
    }
    location.href = url;
    return false;
}